package me.znext.learn.android.game2048publish;

import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import me.znext.learn.android.R;

public class Game2048 extends Activity {

  public Game2048() {
    game2048 = this;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_2048_main);

    LinearLayout root = (LinearLayout) findViewById(R.id.container);
    root.setBackgroundColor(0xfffaf8ef);

    tvScore = (TextView) findViewById(R.id.tvScore);
    tvBestScore = (TextView) findViewById(R.id.tvBestScore);

    gameView = (GameView) findViewById(R.id.gameView);

    Button btnNewGame = (Button) findViewById(R.id.btnNewGame);
    btnNewGame.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        gameView.startGame();
      }
    });

    animLayer = (AnimLayer) findViewById(R.id.animLayer);
  }


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  void clearScore() {
    score = 0;
    showScore();
  }

  private void showScore() {
    tvScore.setText(score + "");
  }

  void addScore(int s) {
    score += s;
    showScore();

    int maxScore = Math.max(score, getBestScore());
    saveBestScore(maxScore);
    showBestScore(maxScore);
  }

  private void saveBestScore(int s) {
    Editor e = getPreferences(MODE_PRIVATE).edit();
    e.putInt(SP_KEY_BEST_SCORE, s);
    e.commit();
  }

  int getBestScore() {
    return getPreferences(MODE_PRIVATE).getInt(SP_KEY_BEST_SCORE, 0);
  }

  void showBestScore(int s) {
    tvBestScore.setText(s + "");
  }

  AnimLayer getAnimLayer() {
    return animLayer;
  }

  private int score = 0;
  private TextView tvScore, tvBestScore;
  private GameView gameView;
  private AnimLayer animLayer = null;

  private static Game2048 game2048 = null;

  static Game2048 getGame2048() {
    return game2048;
  }

  private static final String SP_KEY_BEST_SCORE = "bestScore";

}
